package Windows;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

import Client.ClientListener;
import Client.ClientManager;
import Client.CloseEvent;
import Client.MsgEvent;
import Client.msgRev;
import DBUtil.CNN;
import DBUtil.UserInfo;
import Tools.IMG;
import Windows.DownLoads.NewDownloadFrame;
import Windows.Search.ComplexSearchWindow;
import Windows.Share.SharePathOptionWindow;
import Windows.ShowWindows.ShowWindow;
import Windows.Tree.ResTree;
import Windows.Tree.TreeNodePic;
import Windows.UserWindow.UserInfoPanel;
import WindowsModule.Talking;
import WindowsModule.Update;
import WindowsModule.Yonghuzhuce;
import WindowsModule.Zaohuipassword;
import WindowsModule.Zhiyuanxinxi;
import XML.XML;
import XML.XMLNode;

/**
 * 客户端主界面
 * 
 * @author Administrator
 * 
 */
public class MainWindows extends JFrame implements msgRev, ClientListener, ActionListener {
	public static final TreeNodePic rootNode = new TreeNodePic("ResShare", IMG.root);
	private static MainWindows main;
	public static MainWindows getInstance() {
		if (main == null) {
			try {
//				ShowWindow.PalyWindow();
				AboutWindow.getAboutWindow().setVisible(true);
				AboutWindow.getAboutWindow().setMessage("加载窗口...");
				main = new MainWindows(CNN.getConfig().GetPathValue("User:Title").toString());
				main.Init();
				MainWindows.Tree.jTree.expandRow(0);
				MainWindows.Tree.jTree.updateUI();

			} catch (Exception e) {
				e.printStackTrace();
				AboutWindow.getAboutWindow().setMessageError(e.toString());
			}

		}
		return main;
	}
	public ClientManager client;
	public MainPanel mpanel;// 操作主面板
	private PicPanel mpBg = new PicPanel(IMG.mpg);
	private JPanel topPanel = new JPanel(new BorderLayout());// top主面板
	private PicPanel mpTop = new TopPanel(IMG.banner);
	public static UserInfoPanel jpWeast = new UserInfoPanel();// 左下角
	public static final ResTree Tree = new ResTree(rootNode);// 树形框;//树形框
	public static ComplexSearchWindow csw;
	private JMenuBar jmb;
	private JMenu jmfile;
	private JMenuItem jmnew;
	private JMenuItem jmexit;
	private JMenu jmuser;
	private JMenuItem jmlogin;
	private JMenuItem jmreg;
	private JMenuItem jmupdpass;
	private JMenuItem jmupdinfo;
	private JMenuItem jmout;
	private JMenuItem jmhelp;
	private JMenuItem jmuse;
	private JMenuItem jmabout;;// 工具条
	public final static ResToolBar jToolBar1 = new ResToolBar();
	public final static WindowsModule.Yonghudenglu loginWindows = new WindowsModule.Yonghudenglu();
	public static NewDownloadFrame ndf = null;
	public static SharePathOptionWindow spow = new SharePathOptionWindow();

	private static Zhiyuanxinxi resinfo;

	public static Zhiyuanxinxi getResInfo() {
		if (resinfo == null) {
			resinfo = new Zhiyuanxinxi();
		}
		return resinfo;
	}

	/**
	 * 构造方法
	 * 
	 * @param title
	 * @throws NumberFormatException
	 * @throws UnknownHostException
	 * @throws IOException
	 * @throws IOException
	 */
	public MainWindows(String title) throws IOException {
		super(title+"("+Charset.defaultCharset()+")");
		
	}
	
	public void Init() throws IOException{
		String address = CNN.getConfig().GetPathValue("Serv:address").toString();
		int port = Integer.parseInt(CNN.getConfig().GetPathValue("Serv:port").toString());
		File shareDir = new File(CNN.getConfig().GetPathValue("User.Share:dir").toString());
		AboutWindow.getAboutWindow().setMessage("连接服务器...");
		client = new ClientManager(address, port, shareDir);
		client.addClientListenser(this);

		initMenu();
		mpanel = new MainPanel(IMG.mainP, MainWindows.jToolBar1, rootNode, Tree, client.sp);
		csw = new ComplexSearchWindow(mpanel.getSeachp());
		ndf = new NewDownloadFrame(mpanel.getDownp());
		ndf.jBDownload.addMouseListener(((PicPanel) ndf.jPanel2).getMouseListener());
		Tree.getJTree().addTreeSelectionListener(mpanel);// 注册事件监听器
		Tree.getJTree().addTreeSelectionListener(mpanel.getResp());// 注册事件监听器

		ShowWindow.setWindowICO(this);
		// this.add(Tree,BorderLayout.WEST);
		// this.add(mpanel,BorderLayout.CENTER);
		JSplitPane jspW = new JSplitPane(JSplitPane.VERTICAL_SPLIT, Tree, jpWeast);
		JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jspW, mpanel);
		// jpWeast2.add(new Yonghudenglu().getContentPane());
		jsp.setOneTouchExpandable(true);
		jsp.setContinuousLayout(true);
		jspW.setOneTouchExpandable(true);
		jspW.setContinuousLayout(true);
		this.add(jsp, BorderLayout.CENTER);
		this.pack();
		// this.setBounds(0, 0, d.width, d.height);
		setExtendedState(Frame.MAXIMIZED_BOTH);// 最大化窗口
		// setExtendedState(JFrame.MAXIMIZED_HORIZ);//普通
		// setExtendedState(JFrame.MAXIMIZED_VERT);//普通

		KeyListener kl = new KeyListener() {

			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				if (e.getKeyCode() == 10) {
					Logining();
				}
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub

			}

		};
		loginWindows.jbLogin.addActionListener(this);
		loginWindows.jtfUserName.addKeyListener(kl);
		loginWindows.jPasswordField1.addKeyListener(kl);
		loginWindows.jCheckBox1.addKeyListener(kl);

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//		if(isUndecorated()){
		// com.sun.awt.AWTUtilities.setWindowOpacity(this, 0.8f);//--窗口透明度设置
//		}
		Tree.jTree.updateUI();
		Tree.jTree.addSelectionRow(1);
		Tree.jTree.expandRow(3);// 展开一个结点

		this.addWindowListener(ShowWindow.getOpacityWindowsListener());
		jsp.setDividerLocation(0.20d);
		jspW.setDividerLocation(0.5d);
	}

	/**
	 * 登陆窗口登录按钮被点击
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		Object obj = e.getSource();
		if (obj.getClass() == JButton.class) {
			JButton jb = (JButton) obj;
			if (jb.equals(loginWindows.jbLogin)) {
				Logining();
			}
		}
	}

	@Override
	public void allowFellow(String userID, XML msg) {
		// TODO Auto-generated method stub

	}

	@Override
	public void drop(XML msg) {
		// TODO Auto-generated method stub

	}

	@Override
	public void fettleChange(String userId, int flag) {
		// TODO Auto-generated method stub

	}

	@Override
	public void fllowOline(String UserID, XML msg) {
		// TODO Auto-generated method stub

	}

	public MainPanel getMpanel() {
		return mpanel;
	}

	@Override
	public void groupMessage(int id, String userID, XML msg) {
		// TODO Auto-generated method stub

	}

	private void initMenu() {
		// TODO Auto-generated method stub
		jmb = new JMenuBar();
		jmfile = new JMenu("文件");
		jmnew = new JMenuItem("新建任务");
		jmexit = new JMenuItem("退出");
		jmuser = new JMenu("用户");
		jmlogin = new JMenuItem("用户登陆");
		jmreg = new JMenuItem("用户注册");
		jmupdpass = new JMenuItem("用户资料");
		jmupdinfo = new JMenuItem("找回密码");
		jmout = new JMenuItem("用户注销");
		jmhelp = new JMenu("帮助");
		jmuse = new JMenuItem("使用帮助");
		jmabout = new JMenuItem("关于软件");
		jmb.add(jmfile);
		jmb.add(jmuser);
		jmb.add(jmhelp);
		jmfile.add(jmnew);
		jmfile.add(jmexit);
		jmuser.add(jmlogin);
		jmuser.add(jmreg);
		jmuser.add(jmupdpass);
		jmuser.add(jmupdinfo);
		jmuser.add(jmout);
		jmhelp.add(jmuse);
		jmhelp.add(jmabout);
		this.setJMenuBar(jmb);

		jmuse.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String str = "cmd /c start iexplore " + CNN.getConfig().GetPathValue("User:HelpSite").toString();
				try {
					Runtime.getRuntime().exec(str);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});

		jmabout.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				ShowWindow.PalyWindow(AboutWindow.getAboutWindow());
			}
		});

		jmnew.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				// System.out.println("reg!");
				ndf.setNewTask(new XMLNode(null, "File"), true);
			}
		});

		jmlogin.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				// System.out.println("reg!");
				loginWindows.setVisible(true);
			}
		});
		jmupdinfo.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				// System.out.println("reg!");
				new Zaohuipassword().setVisible(true);
			}
		});
		jmreg.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				// System.out.println("reg!");
				new Yonghuzhuce().setVisible(true);
			}
		});
		jmupdpass.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				new Update().initInfo(client.userid, true);
			}
		});
		jmexit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
		});
		jmout.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				int i = JOptionPane.showConfirmDialog(null, "您真的要注销登陆吗？", "用户注销", JOptionPane.YES_NO_OPTION);
				System.out.println(i);
				if (i == JOptionPane.YES_OPTION) {
					client.login("*", "");
				}
			}
		});
		mpBg.setLayout(new BorderLayout());
		this.setContentPane(mpBg);
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		// -- TOP面版

		topPanel.add(mpTop, BorderLayout.NORTH);
		topPanel.add(jToolBar1, BorderLayout.CENTER);

		this.add(topPanel, BorderLayout.NORTH);
		mpTop.setBounds(0, 0, this.getSize().width, 200);

	}

	public void Logining() {
		String username = loginWindows.jtfUserName.getText();
		String password = loginWindows.jPasswordField1.getText();
		if (username.length() != 0 && password.length() != 0) {
			client.login(username, password);// 登陆服务器
			loginWindows.setVisible(false);

			XMLNode xf = (XMLNode) (CNN.getConfig().GetPathValue("User"));
			xf.put("id", loginWindows.jCheckBox1.isSelected() ? loginWindows.jtfUserName.getText() : "*");
			xf.put("pwd", loginWindows.jCheckBox1.isSelected() ? loginWindows.jPasswordField1.getText() : "");
			CNN.getConfig().createCode(new File("Config.xml"));

		}
	}

	@Override
	public void message(String userID, XML msg) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCloseEvent(CloseEvent cce) {
		JOptionPane.showMessageDialog(null, "服务器连接断开！");
	}

	@Override
	public void onlineDown(String UserID, XML msg) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMsgEvent(MsgEvent ce) {
		String flg = ce.getCmd().FLAG;// --取大写的指令
		XML cmd = ce.getCmd();
		if (flg.equalsIgnoreCase("talk")) {// ---打开聊天
			if (cmd.get("open") != null) {
				new Talking(ce.getCmd()).setVisible(true);
			}
		} else if (flg.equalsIgnoreCase("userinfo")) {// ---群消息
			long onlineTime = Long.parseLong(cmd.get("online_time"));
			UserInfo ui = new UserInfo(client.userid, cmd.getInt("integer"), cmd.getInt("grade"), onlineTime);
			jpWeast.setUser(ui);
			// c.groupMessage(Integer.parseInt(cmd.get("id")), cmd
			// .get("UserID"), cmds.remove(cmd));
		} else if (flg.equalsIgnoreCase("groupmsg")) {// ---群消息
			// c.groupMessage(Integer.parseInt(cmd.get("id")), cmd
			// .get("UserID"), cmds.remove(cmd));
		} else if (flg.equalsIgnoreCase("drop")) {// ---掉线提示，在其他地方登陆被挤下
			// c.drop(cmds.remove(cmd));

		} else if (flg.equalsIgnoreCase("online")) {// ---网友上线通知
			// c.fllowOline(cmd.get("UserID"), cmds.remove(cmd));

		} else if (flg.equalsIgnoreCase("outline")) {// ---网友下线通知
			// c.onlineDown(cmd.get("UserID"), cmds.remove(cmd));

		} else if (flg.equalsIgnoreCase("msg")) {// ---网友消息
			// c.message(cmd.get("UserID"), cmds.remove(cmd));
		} else if (flg.equalsIgnoreCase("add")) {// ---申请加好友
			// c.allowFellow(cmd.get("UserID"), cmds.remove(cmd));
		}else if(flg.equalsIgnoreCase("Outline")){
			JOptionPane.showMessageDialog(this, "其他地方登录您的账号，被服务器踢下线！");
		}
	}

	@Override
	public void resPip(String md5, String address, int port, String UserID, XML data) {
		// TODO Auto-generated method stub

	}

	@Override
	public void Revmsg(String userId, String msg, Date time) {
		// TODO Auto-generated method stub

	}

	@Override
	public void SResault(int id, String UserID, XML sr) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sysMsg(String msg) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sysMsg(XML msg) {
		// TODO Auto-generated method stub

	}

}
